package cn.xuxiu.org.service.impl;

import cn.xuxiu.bacsic.service.impl.BaseServiceImpl;
import cn.xuxiu.org.domain.Department;
import cn.xuxiu.org.mapper.DepartmentMapper;
import cn.xuxiu.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
@Transactional(readOnly = true ,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    @Transactional
    public void save(Department department) {
        departmentMapper.save(department);
        this.update(department);
    }

    @Override
    @Transactional
    public void update(Department department) {
        String dirPath="";
        if (department.getParent() == null){
            dirPath = "/" + department.getId();
        } else {
            Department parent = departmentMapper.loadById(department.getParent().getId());
            dirPath = parent.getDirPath() + "/" + department.getId();
        }
        department.setDirPath(dirPath);
        departmentMapper.update(department);
    }

    @Override
    public List<Department> deptTree() {
        List<Department> departments = departmentMapper.loadAll();
        HashMap<Long, Department> map = new HashMap<>();
        for (Department department : departments){
            // 将所有的部门放在hashmap中
            map.put(department.getId(),department);
        }
        List<Department> firstDepts = new ArrayList<>();
        for (Department dep : departments){
            // 如果上级部门是空那么就是顶级部门
            if (dep.getParent_id() == null){
                firstDepts.add(dep);
            } else {
                // parent这是将上级部门的id获取出来，用map获取到对象就是该部门的父级
                Department parent = map.get(dep.getParent_id());
                if(parent != null){
                    // 将对象装给上级部门
                    parent.getChildren().add(dep);
                }
            }
        }
        return firstDepts;
    }
}
